import 'package:json_annotation/json_annotation.dart';

part 'browsing_recipe_history_api.g.dart';

@JsonSerializable()
class ResponseBrowsingRecipeHistoryApi {
  final int total;
  final List<RecipeHistory> rows;

  ResponseBrowsingRecipeHistoryApi({required this.total, required this.rows});

  factory ResponseBrowsingRecipeHistoryApi.fromJson(
    Map<String, dynamic> json,
  ) => _$ResponseBrowsingRecipeHistoryApiFromJson(json);

  Map<String, dynamic> toJson() =>
      _$ResponseBrowsingRecipeHistoryApiToJson(this);
}

@JsonSerializable()
class RecipeHistory {
  final String? author;
  final String id;
  final String? mainImg;
  final String? name;
  final String? desc;
  final String? likes;
  final String? view;
  final String? collection;
  final int? isControl;
  final String? createTime;

  factory RecipeHistory.fromJson(Map<String, dynamic> json) {
    final info = json['remoteRecipeMenuInfoVo'] ?? {};
    return RecipeHistory(
      author: json['author'] ?? '',
      id: info['id'] ?? '',
      name: info['name'] ?? '',
      mainImg: _getImageUrl(info) ?? '',
      desc: info['name'] ?? '',
      view: info['view'],
      likes: info['likes'],
      collection: info['collection'],
      isControl: info['isControl'],
      createTime: json['createTime'] ?? '',
    );
  }

  RecipeHistory({
    required this.author,
    required this.id,
    required this.mainImg,
    required this.name,
    required this.desc,
    required this.likes,
    required this.view,
    required this.collection,
    required this.isControl,
    required this.createTime,
  });

  static String? _getImageUrl(Map<dynamic, dynamic> json) {
    final Map<String, dynamic> safeJson = Map<String, dynamic>.from(json);
    if (safeJson['mainImg'] != null && safeJson['mainImg'] is String) {
      String mainImg = safeJson['mainImg'];
      if (mainImg.isNotEmpty) return mainImg;
    }

    if (safeJson['imageUrls'] != null && safeJson['imageUrls'] is String) {
      String imageUrls = safeJson['imageUrls'];
      if (imageUrls.isNotEmpty) return imageUrls.split(',').first;
    }

    return null;
  }
}
